-- lua/lingma/core.lua
-- 核心逻辑：调用 Qwen API

local M = {}

M.api_key = nil
M.model = "qwen3-coder-plus"

local function get_api_key()
  return M.api_key or os.getenv("DASHSCOPE_API_KEY")
end

-- 主请求函数：优先使用 vim.http，失败则回退到 curl
function M.request_completion(messages, callback)
  local key = get_api_key()
  if not key then
    vim.notify("未设置 DASHSCOPE_API_KEY", vim.log.levels.ERROR)
    callback(nil, "API key missing")
    return
  end

  -- 优先使用 vim.http，否则回退到 curl
  if vim.http and vim.http.request then
    M._request_with_http(messages, key, callback)
  else
    -- vim.notify("vim.http 不可用，使用 curl 回退...", vim.log.levels.WARN)
    M._request_with_curl(messages, key, callback)
  end
end

-- 使用 vim.http 发起请求
function M._request_with_http(messages, api_key, callback)
  local url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"

  local body = vim.json.encode({
    model = M.model or "qwen3-coder-plus",  -- 可配置模型
    messages = messages,                   -- 直接传入 messages 数组
    -- temperature, max_tokens 等可选参数也可加在这里
  })

  local headers = {
    ["Authorization"] = "Bearer " .. api_key,
    ["Content-Type"] = "application/json"
  }

  vim.http.request(url, {
    method = "POST",
    headers = headers,
    body = body,
  }, function(response)
    if not response then
      return callback(nil, "HTTP 请求失败：无响应")
    end

    if response.status == 200 then
      local ok, data = pcall(vim.json.decode, response.body)
      if ok and data and data.choices and #data.choices > 0 then
        local content = data.choices[1].message.content
        return callback(content)  -- 成功返回补全内容
      else
        local err_msg = (data and data.error and data.error.message) or "解析失败：无效响应"
        vim.notify("响应解析失败: " .. err_msg, vim.log.levels.WARN)
        return callback(nil, err_msg)
      end
    else
      local err = string.format("HTTP %d: %s", response.status, response.body or "Unknown error")
      vim.notify("❌ API 请求失败: " .. err, vim.log.levels.ERROR)
      return callback(nil, err)
    end
  end)
end

-- check job status
local function check_job_status(job_id)
  if not job_id or job_id <= 0 then
    return "invalid" -- 无效的任务 ID
  end

  -- 使用 vim.fn.jobwait 检查任务状态
  local result = vim.fn.jobwait({ job_id }, 0) -- 0 表示非阻塞检查
  if result[1] == -1 then
    return "running" -- 任务正在运行
  elseif result[1] == 0 then
    return "completed" -- 任务已完成
  else
    return "failed" -- 任务失败
  end
end

-- 使用 curl 回退
function M._request_with_curl(messages, api_key, callback)
  local url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"

  local body = vim.json.encode({
    model = M.model or "qwen3-coder-plus",
    messages = messages
  })

  local cmd = {
    "curl", "-s", "-X", "POST",
    "-H", "Content-Type: application/json",
    "-H", "Authorization: Bearer " .. api_key,
    "--data", body,
    url
  }

  local job_id = vim.fn.jobstart(cmd, {
    stdout_buffered = true,
    on_stdout = function(_, chunks, _)
      local response_body = table.concat(chunks, "")
      if response_body == "" then
        vim.notify("❌ curl 返回空响应", vim.log.levels.ERROR)
        return callback(nil, "Empty response")
      end

      local ok, data = pcall(vim.json.decode, response_body)
      if ok and data and data.choices and #data.choices > 0 then
        local content = data.choices[1].message.content
        callback(content)
      else
        local err_msg = (data and data.error and data.error.message) or "JSON 解析失败"
        vim.notify("❌ curl 失败: " .. err_msg, vim.log.levels.ERROR)
        callback(nil, err_msg)
      end
    end,
    on_stderr = function(_, chunks, _)
      local err = table.concat(chunks, "")
      if not vim.tbl_isempty(chunks) and not err:match("^%s*$") then
        vim.notify("curl 错误: " .. err, vim.log.levels.DEBUG)
      end
    end,
    on_exit = function(_, exit_code, _)
      if exit_code ~= 0 then
        vim.notify("curl 退出码: " .. exit_code, vim.log.levels.ERROR)
      end
    end,
  })

  -- 30秒超时
  vim.defer_fn(function()
    local status = check_job_status(job_id)
    if status == "running" then
      vim.notify("任务正在运行", vim.log.levels.INFO)
    elseif status == "completed" then
      vim.notify("任务已完成", vim.log.levels.INFO)
    else
      vim.notify("任务已销毁", vim.log.levels.INFO)
    end
  end, 30000)
end

return M
